package com.skytech.tax.customsdatawarehouse.electronicport.customsdeclarations.domain.dao;

import com.skytech.tax.customsdatawarehouse.electronicport.customsdeclarations.domain.entity.CustomsDeclarationSimple;
import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Lianhong
 * @since 2021/6/10
 */
@Repository("electronicPort.customsDeclarationSimpleDao")
public class CustomsDeclarationSimpleDao {

    @Resource
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    private String saveCustomsDeclarationSimpleSql = "INSERT INTO gd_cardhead_simple (entryId, iEDate) VALUES (:entryId, :iEDate)";

    public void save(CustomsDeclarationSimple customsDeclarationSimple) {
        namedParameterJdbcTemplate.update(this.saveCustomsDeclarationSimpleSql, new BeanPropertySqlParameterSource(customsDeclarationSimple));
    }

    private String existsCustomsDeclarationSimpleSql = "SELECT count(1) FROM gd_cardhead_simple WHERE entryId = ?";

    public boolean exists(String entryId, String iEDate) {
        StringBuilder builder = new StringBuilder(existsCustomsDeclarationSimpleSql);
        Object[] params = new Object[]{entryId};
        if (StringUtils.isNotBlank(iEDate)) {
            builder.append(" and iEDate = ?");
            params = new Object[]{entryId, iEDate};
        }
        return Boolean.TRUE.equals(namedParameterJdbcTemplate.getJdbcOperations()
                .queryForObject(builder.toString(), params, boolean.class));
    }

    private String deleteCustomsDeclarationSimpleSql = "DELETE FROM gd_cardhead_simple WHERE entryId = ?";

    public void delete(String entryId) {
        this.namedParameterJdbcTemplate.getJdbcOperations().update(this.deleteCustomsDeclarationSimpleSql, entryId);
    }

    private String existsCustomsDeclarationsSimpleSql = "SELECT entryId FROM gd_cardhead_simple WHERE (entryId, iEDate) in (%s) GROUP BY entryId";

    public List<String> exists(List<CustomsDeclarationSimple> simpleList) {
        List<String> params = new ArrayList<>();
        simpleList.forEach(item -> params.add("('" + item.getEntryId() + "','" + item.getiEDate() + "')"));
        String sql = String.format(this.existsCustomsDeclarationsSimpleSql, StringUtils.join(params, ","));
        return this.namedParameterJdbcTemplate.getJdbcOperations().queryForList(sql, String.class);
    }
}
